<?php

namespace App\Services;

use App\Models\User;
use Illuminate\Support\Collection;

class UserAbilityService extends BaseService
{
    protected $user;

    /**
     * Get all roles or get first role.
     *
     * @param string $role
     * @return mixed
     * @author Bob <bob@bobcoder.cc>
     */
    public function roles(string $role = '')
    {
        $roles = $this->user()
            ->roles()
            ->get()
            ->keyBy('name');

        if (!$role) {
            return $roles;
        }

        return $roles->get($role, false);
    }

    /**
     * Get all abilities or get first ability.
     *
     * @param string $ability
     * @return mixed
     * @author Bob <bob@bobcoder.cc>
     */
    public function all(string $ability = '')
    {
        $roles = $this->roles();
        $roles->load('abilities');
        $abilities = $roles->reduce(function ($collect, $role) {
            return $collect->merge(
                $role->abilities->keyBy('name')
            );
        }, new Collection());

        if (!$ability) {
            return $abilities;
        }

        return $abilities->get($ability, false);
    }

    /**
     * @return mixed
     * @author Bob(bobcoder@qq.com)
     */
    public function menus()
    {
        $roles = $this->roles();
        $roles->load('abilities_menus');
        $abilities = $roles->reduce(function ($collect, $role) {
            return $collect->merge(
                $role->abilities_menus->keyBy('name')
            );
        }, new Collection());

        return $abilities;
    }

    /**
     * Get user instance.
     *
     * @return \App\Models\User
     * @author Bob <bob@bobcoder.cc>
     */
    public function user(): User
    {
        return $this->user;
    }

    /**
     * Set user model.
     *
     * @param User $user
     * @return UserAbilityService
     * @author Bob <bob@bobcoder.cc>
     */
    public function setUser(User $user)
    {
        $this->user = $user;

        return $this;
    }
}
